package com.lsk.common.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Action;
import com.jfinal.core.Controller;
import com.jfinal.render.JsonRender;
import com.jfinal.render.Render;
import com.jfinal.render.TextRender;
import com.jfinal.render.XmlRender;
import com.lsk.util.DateUtil;
import com.lsk.util.IPHelper;
import com.lsk.util.ReturnData;
import com.lsk.util.Syslog;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

/**
 * Created by Administrator on 2018/4/13 0013.
 */
public class CacheInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation invocation) {
        /*请求参数打印*/

        String currentTime=System.currentTimeMillis()+"";
        invocation.getController().setUrlPara(currentTime);

        Controller controller=invocation.getController();

        HttpServletRequest request=controller.getRequest();


        HttpServletResponse response=controller.getResponse();
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires", -10);



        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token,XMLHttpRequest,token");
        response.setHeader("Access-Control-Allow-Credentials", "true");


        if ("OPTIONS".equalsIgnoreCase(request.getMethod())){

            /*controller.renderJson(new ReturnData());

            invocation.invoke();*/
            controller.renderNull();
            return;
        }

        int maxOutputLengthOfParaValue = 512;

        String ip= IPHelper.getIpAddress(request);

        StringBuilder sb = (new StringBuilder("\n 郑州鼎原信息技术有限公司-------- ")).append(DateUtil.getTime()).append(" ------------------------------\n");
        sb.append("Url         : ").append(controller.getRequest().getRequestURI()).append("\n");
        sb.append("ip          : ").append(ip);
        sb.append("\nMethod      : ").append(request.getMethod()).append("\n");
        String urlParas = controller.getPara();
        if (urlParas != null) {
            sb.append("UrlPara     : ").append(urlParas).append("\n");
        }


        Enumeration<String> e = request.getParameterNames();
        if (e.hasMoreElements()) {
            sb.append("Parameter   : ");

            for(; e.hasMoreElements(); sb.append("  ")) {
                String name = (String)e.nextElement();
                String[] values = request.getParameterValues(name);
                if (values.length == 1) {
                    sb.append(name).append("=");
                    if (values[0] != null && values[0].length() > maxOutputLengthOfParaValue) {
                        sb.append(values[0].substring(0, maxOutputLengthOfParaValue)).append("...");
                    } else {
                        sb.append(values[0]);
                    }
                } else {
                    sb.append(name).append("[]={");

                    for(int i = 0; i < values.length; ++i) {
                        if (i > 0) {
                            sb.append(",");
                        }

                        sb.append(values[i]);
                    }

                    sb.append("}");
                }
            }

            sb.append("\n");
        }

        /*cookies*/
        Cookie[] cookies = request.getCookies();

        if (cookies!=null){
            if (cookies.length>0){

                sb.append("cookies    : ");

                sb.append("[]={");
            }

            for (int i=0;i<cookies.length;i++){

                Cookie cookie=cookies[i];

                String name=cookie.getName();

                String value=cookie.getValue();

                sb.append("\n "+name+" : "+value);

            }

            if (cookies.length>0){

                sb.append("\n }");
            }
        }






        sb.append("--------------------------------------------------------------------------------\n");




        invocation.invoke();

        /*拦截打印返回值*/
//        try {
//
//            Render r = controller.getRender();
//            if (r instanceof JsonRender) {
//
//                sb.append("********UrlPara :"+controller.getPara()+" *********\n");
//
//                String JsonText = ((JsonRender)r).getJsonText();
//                // JsonText 处理
//                sb.append("********返回的json数据*********\n");
//                sb.append(JsonText);
//            }else if (r instanceof TextRender) {
//
//                sb.append("********UrlPara :"+controller.getPara()+" *********\n");
//                String JsonText = ((JsonRender)r).getJsonText();
//                // JsonText 处理
//                sb.append("********返回的文本数据*********\n");
//                sb.append(JsonText);
//            }else if (r instanceof XmlRender) {
//
//                sb.append("********UrlPara :"+controller.getPara()+" *********\n");
//                String JsonText = ((JsonRender)r).getJsonText();
//                // JsonText 处理
//                sb.append("********返回的XML数据*********\n");
//                sb.append(JsonText);
//            }
//        } catch (Exception e1) {
//            //异常处理
//            Syslog.error(e1);
//
//        }
        Syslog.info(sb.toString());

    }
}
